package com.xinshujia.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xinshujia.entity.UserEntity;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author: 野狼上校
 * @create: 2023-03-20  11:38
 * @version: 1.0
 * @description: Jwt工具
 */
@Component
public class JwtUtil {
    /* 创建token */
    public String createToken(UserEntity user) {
        //过期时间 -- 24小时
        Date expireDate = new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000);
        //header
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HMAC256");
        map.put("typ", "JWT");
        return JWT.create()
                //header
                .withHeader(map)
                //payload
                .withClaim("id", user.getId())
                .withClaim("username", user.getUsername())
                //过期时间
                .withExpiresAt(expireDate)
                //签发时间
                .withIssuedAt(new Date())
                //加密方式或密钥(sign)
                .sign(Algorithm.HMAC256(Constants.SECRET_KEY));
    }


    /* 解析token */
    public DecodedJWT parseToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(Constants.SECRET_KEY)).build();
        return jwtVerifier.verify(token);
    }

    public static void main(String[] args) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(2L);
        userEntity.setUsername("shangxiao111");

        JwtUtil jwtUtil = new JwtUtil();
        String token = jwtUtil.createToken(userEntity);
        System.out.println(token);


        DecodedJWT decodedJWT = jwtUtil.parseToken(token);
        System.out.println(decodedJWT.getClaim("username"));
    }
}
